import { Button, Form, Input, Tabs, message } from "antd";
import { LockIcon, MailIcon } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router";
import { apiLogin, apiProfile } from "~/api";
import { useUserInfo } from "~/contexts/user-info";
import { setToken } from "~/utils/auth";
import http from "~/utils/http";

type LoginType = "password" | "verifyCode";

export default function Login() {
  const [loginType, setLoginType] = useState<LoginType>("password");
  const [verifyCodeLoading, setVerifyCodeLoading] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { setUserInfo } = useUserInfo();

  // 获取验证码
  const getVerifyCode = async () => {
    const email = form.getFieldValue("email");
    if (!email) {
      message.error("请输入邮箱地址");
      return;
    }

    try {
      setVerifyCodeLoading(true);
      await http.post("/auth/send-verify-code", { email });
      message.success("验证码已发送");
    } finally {
      setVerifyCodeLoading(false);
    }
  };

  // 提交登录
  const onFinish = async (values: { email: string; password: string }) => {
    try {
      const resp = await apiLogin(values);
      message.success("登录成功");
      setToken(resp.token);
      const userInfo = await apiProfile();
      setUserInfo(userInfo);
      navigate(userInfo.permissions[0]?.children?.[0]?.path || "/404", {
        replace: true,
      });
      navigate("/manage", { replace: true });
    } catch (error) {
      console.error("登录失败", error);
    }
  };

  return (
    <div className="flex h-screen items-center justify-center bg-gray-100">
      <div className="w-[400px] rounded-xl bg-white p-8 shadow-lg">
        <h1 className="mb-6 text-center text-2xl font-bold">欢迎登录</h1>

        <Tabs
          activeKey={loginType}
          onChange={(key) => setLoginType(key as LoginType)}
          centered
          items={[
            { key: "password", label: "密码登录" },
            { key: "verifyCode", label: "验证码登录" },
          ]}
        />

        <Form form={form} onFinish={onFinish} className="mt-6">
          <Form.Item
            name="email"
            rules={[
              { required: true, message: "请输入邮箱地址" },
              { type: "email", message: "请输入有效的邮箱地址" },
            ]}
          >
            <Input addonBefore={<MailIcon size={16} />} placeholder="邮箱" />
          </Form.Item>

          {loginType === "password" ? (
            <Form.Item
              name="password"
              rules={[{ required: true, message: "请输入密码" }]}
            >
              <Input.Password
                addonBefore={<LockIcon size={16} />}
                placeholder="密码"
              />
            </Form.Item>
          ) : (
            <div className="flex gap-2">
              <Form.Item
                name="code"
                rules={[{ required: true, message: "请输入验证码" }]}
                className="flex-1"
              >
                <Input placeholder="邮箱验证码" />
              </Form.Item>
              <Button
                loading={verifyCodeLoading}
                onClick={getVerifyCode}
                className="w-32"
              >
                获取验证码
              </Button>
            </div>
          )}

          <Form.Item>
            <Button type="primary" htmlType="submit" block className="mt-4">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
